<template>
  <d2-container>
    <el-row :gutter="20">
      <el-col :span="5">
        <el-scrollbar :style="'height:100%;width: 100%'">
          <area-tree @nodeChange="treeNodeChange"></area-tree>
        </el-scrollbar>
      </el-col>
      <el-col :span="19">
        <div class="device-btn-box">
          <div class="radio-box">
            <el-checkbox v-model="allCheck" @change="clickAll">全选</el-checkbox>
          </div>
          <div>
            <el-button  @click="printContent" size="medium" style="float: right" :disabled="getCheckedList().length<=0">打印 </el-button>
          </div>
        </div>

        <div class="printSection" :style="{ display: 'flex', flexWrap: 'wrap', gap: '20px' }">
          <div v-for="(param, index) in dataList" :key="param.meterCode" class="qr-image-container">
            <el-checkbox v-model="checkedList[index]"></el-checkbox>
            <img :src="'data:image/png;base64,'+param.qrImage" alt="示例图片" v-if="param.qrImage && param.qrImage!=''">
            <span v-else>{{param.meterCode}}还未生成二维码</span>
          </div>
        </div>

      </el-col>
    </el-row>
  </d2-container>
</template>

<script>
  import { mapGetters } from 'vuex'
  import areaTree from '../energyAnalysis/compont/area_tree'
  import dayjs from 'dayjs'
  import * as Util from "@/utils";
  export default {
    name: 'deviceQr',
    data() {
      return {
        allCheck: false,
        buildList:[],
        dataList:[],
        meterTypeList:[],
        currentUnit:"",
        checkedList: []
      }
    },
    computed: {
      ...mapGetters('d2admin/theme', ['activeSetting'])
    },
    components: {
      areaTree
    },
    created() {
      this.$nextTick(()=>{
        this.queryStatic("METER_TYPE",null,data=>{
          if (data && data.code === 0) {
            this.meterTypeList = data.page
            this.dataForm.energyType = data.page[0].paramKey;
            this.currentUnit = data.page[0].paramExt;
          } else {
            this.meterTypeList = []
          }
          // this.getPowerDataList();
        });
      })
    },
    methods: {
      printContent() {
        const checkedImages = [];
        this.dataList.forEach((param, index) => {
          if (this.checkedList[index]) {
            if (param.qrImage && param.qrImage!='') {
              // 添加样式确保图片在打印时保持正确尺寸
              checkedImages.push(`<img src="data:image/png;base64,${param.qrImage}" alt="示例图片" style="max-width: 100%; height: auto;">`);
            } else {
              checkedImages.push(`<span>${param.meterCode}还未生成二维码</span>`);
            }
          }
        });
        const content = checkedImages.join('');
        const newWin = window.open();
        // 添加样式表确保打印布局正确
        newWin.document.write(`<html><head><style>body { margin: 0; padding: 20px; } .printSection { display: flex; flex-wrap: wrap; gap: 20px; } .qr-image-container { flex: 0 0 calc(20% - 20px); }</style></head><body><div class="printSection">${content}</div></body></html>`);
        newWin.document.close(); // 必要，否则在IE中会阻止打印功能
        newWin.print();
        newWin.close(); // 完成后关闭窗口，根据需要决定是否关闭
      },
      queryStatic(type,paramValue,callback) {
        let params = {
          'code': type ,
          "customerId":this.$util.cookies.get('customer_id')
        }
        if(paramValue){
          Object.assign(params,{paramValue,paramValue});
        }
        this.$api.okhttp({
          url: this.$http.adornUrl('/sys/sysstaticdata/getList'),
          method: 'get',
          params: this.$http.adornParams(params)
        }).then((data) => {
          if(callback){
            callback(data);
          }
        });
      },
      treeNodeChange(data){
        this.buildList = data
        this.getPowerDataListAll()
      },
      getPowerDataListAll(showType){
        if(this.buildList.length <= 0){
          this.dataList = []
          this.checkedList = []
          return
        }

        this.$api.okhttp({
          url: '/ecs/ecsbuildingmeter/devicelist',
          method: 'post',
          data: this.$http.adornParams(
            {
              buildingIds: this.buildList,
              customerId: this.$util.cookies.get("customer_id"),
              projectId:this.$util.cookies.get("cuuren_projectId")
            }
          )
        }).then((data) => {
          if (data && data.code === 0) {
            this.dataList = data.page
            this.checkedList = new Array(this.dataList.length).fill(false)
          } else {
            this.dataList = []
            this.checkedList = []
          }
        })
      },
      clickAll(checked) {
        this.checkedList = new Array(this.dataList.length).fill(checked);
      },
      getCheckedList() {
        return this.checkedList.filter(Boolean);
      }
    }
  }
</script>

<style>
  .device-btn-box {
    height: 38px;
    overflow: hidden;
    clear: both;
    margin: 20px;
  }

  .radio-box {
    float: left;
    margin-top: 2px;
  }
</style>

<style scoped>
  .qr-image-container {
    flex: 0 0 calc(20% - 20px);
  }

  @media print {
    .printSection {
      display: flex;
      flex-wrap: wrap;
      gap: 20px;
    }
    .qr-image-container {
      flex: 0 0 calc(20% - 20px); /* 默认每排 5 个 */
    }
  }
</style>
